package com.tjec.project.businessWorkbench.service.impl;

import com.tjec.common.constant.AttachmentConstants;
import com.tjec.common.constant.Constants;
import com.tjec.common.utils.DateUtils;
import com.tjec.common.utils.ServletUtils;
import com.tjec.common.utils.StringUtils;
import com.tjec.framework.security.service.TokenService;
import com.tjec.project.businessWorkbench.domain.ArchiveStatusVo;
import com.tjec.project.businessWorkbench.domain.BmsArchivedAttachment;
import com.tjec.project.businessWorkbench.domain.BmsBusiness;
import com.tjec.project.businessWorkbench.domain.BmsBusinessDocArchive;
import com.tjec.project.businessWorkbench.domain.BmsBusinessPickup;
import com.tjec.project.businessWorkbench.domain.DocArchiveVo;
import com.tjec.project.businessWorkbench.dto.BmsAttachmentDto;
import com.tjec.project.businessWorkbench.mapper.BmsBusinessDocArchiveMapper;
import com.tjec.project.businessWorkbench.mapper.BmsBusinessMapper;
import com.tjec.project.businessWorkbench.service.IBmsBusinessDocArchiveService;
import com.tjec.project.system.mapper.BmsAttachmentMapper;
import com.tjec.project.system.service.IBmsAttachmentProjectBusinessService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 资料归档Service业务层处理
 *
 * @author pangyongfeng
 * @date 2020-05-18
 */
@Service
public class BmsBusinessDocArchiveServiceImpl implements IBmsBusinessDocArchiveService {
	@Autowired
	private BmsBusinessDocArchiveMapper bmsBusinessDocArchiveMapper;

	@Autowired
	private BmsAttachmentMapper bmsAttachmentMapper;

	@Autowired
	private TokenService tokenService;

	@Autowired
	private BmsBusinessMapper bmsBusinessMapper;

	@Autowired
	private IBmsAttachmentProjectBusinessService bmsAttachmentProjectBusinessService;

	@Value("${sftp.http}")
	private String http;
	@Value("${sftp.ip}")
	private String ip;

	/**
	 * 查询资料归档
	 *
	 * @param guid 资料归档ID
	 * @return 资料归档
	 */
	@Override
	public BmsBusinessDocArchive selectBmsBusinessDocArchiveByGuid(String guid) {
		BmsBusinessDocArchive result = bmsBusinessDocArchiveMapper.selectBmsBusinessDocArchiveByGuid(guid);
		if (result != null && result.getAttachments() != null && result.getAttachments().size() == 1
				&& result.getAttachments().get(0).getFileId() == null) {
			result.setAttachments(null);
		} else {
			result.getAttachments().forEach(it -> {
				if (StringUtils.isNotBlank(it.getFileId())) {
					it.setStoragePath(http + ip + Constants.RESOURCE_PREFIX + it.getStoragePath());
				}
			});
		}
		return result;
	}

	/**
	 * 查询资料归档列表
	 *
	 * @param bmsBusinessDocArchive 资料归档
	 * @return 资料归档
	 */
	@Override
	public List<BmsBusinessDocArchive> selectBmsBusinessDocArchiveList(BmsBusinessDocArchive bmsBusinessDocArchive) {

		List<BmsBusinessDocArchive> list = bmsBusinessDocArchiveMapper
				.selectBmsBusinessDocArchiveList(bmsBusinessDocArchive);
		list.forEach(item -> {
			List<BmsAttachmentDto> attachments = item.getAttachments();
			if (attachments != null && attachments.size() > 0) {
				attachments.forEach(it -> {
					if (StringUtils.isNotBlank(it.getFileId())) {
						it.setStoragePath(http + ip + Constants.RESOURCE_PREFIX + it.getStoragePath());
					}
				});
			}
		});
		return list;
	}

	/**
	 * 查询资料归档列表
	 *
	 * @param bmsBusinessDocArchive 资料归档
	 * @return 资料归档
	 */
	@Override
	public List<BmsBusinessDocArchive> selectBmsBusinessDocArchiveListInDoc(
			BmsBusinessDocArchive bmsBusinessDocArchive) {

		List<BmsBusinessDocArchive> list = bmsBusinessDocArchiveMapper
				.selectBmsBusinessDocArchiveListInDoc(bmsBusinessDocArchive);
		list.forEach(item -> {
			List<BmsAttachmentDto> attachments = item.getAttachments();
			if (attachments != null && attachments.size() > 0) {
				attachments.forEach(it -> {
					if (StringUtils.isNotBlank(it.getFileId())) {
						it.setStoragePath(http + ip + Constants.RESOURCE_PREFIX + it.getStoragePath());
					}
				});
			}
		});
		return list;
	}

	/**
	 * 新增资料归档
	 *
	 * @param bmsBusinessDocArchive 资料归档
	 * @return 结果
	 */
	@Override
	public int insertBmsBusinessDocArchive(BmsBusinessDocArchive bmsBusinessDocArchive) {
		bmsBusinessDocArchive.setCreateTime(DateUtils.getNowDate());
		return bmsBusinessDocArchiveMapper.insertBmsBusinessDocArchive(bmsBusinessDocArchive);
	}

	/**
	 * 修改资料归档
	 *
	 * @param bmsBusinessDocArchive 资料归档
	 * @return 结果
	 * @throws Exception
	 */
	@Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	@Override
	public int updateBmsBusinessDocArchive(BmsBusinessDocArchive bmsBusinessDocArchive) throws Exception {
		int result = bmsBusinessDocArchiveMapper.updateBmsBusinessDocArchive(bmsBusinessDocArchive);
		if (result <= 0)
			throw new Exception("资料归档修改失败！");

		String[] guIds = { bmsBusinessDocArchive.getGuid() };
		bmsAttachmentMapper.updateBmsAttachmentByGuids(guIds,
				tokenService.getLoginUser(ServletUtils.getRequest()).getUser().getUserId());

		if (bmsBusinessDocArchive.getAttachmentIds() != null && bmsBusinessDocArchive.getAttachmentIds().size() > 0) {

			int updateRes = bmsAttachmentMapper.updateBmsAttachmentArchive(bmsBusinessDocArchive.getAttachmentIds(),
					bmsBusinessDocArchive.getGuid(), AttachmentConstants.BUSINESS_DOC,
					tokenService.getLoginUser(ServletUtils.getRequest()).getUser().getUserId());

			bmsAttachmentProjectBusinessService.insertBmsAttachmentProjectBusinessByBusinessId(
					bmsBusinessDocArchive.getAttachmentIds(), bmsBusinessDocArchive.getBusinessId());

			List<String> archiveIds = new ArrayList<String>();
			archiveIds.add(bmsBusinessDocArchive.getGuid());

			bmsBusinessDocArchiveMapper.deleteBmsArchivedAttachmentByArchiveIds(archiveIds);

			List<BmsArchivedAttachment> bmsArchivedAttachments = new ArrayList<BmsArchivedAttachment>();

			for (int i = 0; i < bmsBusinessDocArchive.getAttachmentVos().size(); i++) {
				BmsArchivedAttachment bmsArchivedAttachment = new BmsArchivedAttachment();
				bmsArchivedAttachment.setArchiveId(bmsBusinessDocArchive.getGuid());
				bmsArchivedAttachment
						.setAttachmentId(bmsBusinessDocArchive.getAttachmentVos().get(i).getAttachmentId());
				bmsArchivedAttachment.setFileSource(bmsBusinessDocArchive.getAttachmentVos().get(i).getFileSource());
				bmsArchivedAttachments.add(bmsArchivedAttachment);
			}
			if (bmsArchivedAttachments.size() > 0) {
				bmsBusinessDocArchiveMapper.insertBmsArchivedAttachment(bmsArchivedAttachments);
			}

			return 1;
		} else {
			List<String> archiveIds = new ArrayList<String>();
			archiveIds.add(bmsBusinessDocArchive.getGuid());
			int res = bmsBusinessDocArchiveMapper.deleteBmsArchivedAttachmentByArchiveIds(archiveIds);

			return 1;
		}
	}

	/**
	 * 批量删除资料归档
	 *
	 * @param guids 需要删除的资料归档ID
	 * @return 结果
	 * @throws Exception
	 */
	@Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	@Override
	public int deleteBmsBusinessDocArchiveByGuids(String[] guids) throws Exception {
		// 首先，逻辑删除该文件标题下的所有附件
		int res = bmsAttachmentMapper.updateBmsAttachmentByGuids(guids,
				tokenService.getLoginUser(ServletUtils.getRequest()).getUser().getUserId());

		if (res < 0)
			throw new Exception("逻辑删除文件标题下的附件失败，guids=" + guids);
		List<String> archiveIds = new ArrayList<String>();
		Collections.addAll(archiveIds, guids);
		bmsBusinessDocArchiveMapper.deleteBmsArchivedAttachmentByArchiveIds(archiveIds);

		return bmsBusinessDocArchiveMapper.deleteBmsBusinessDocArchiveByGuids(guids);
	}

	/**
	 * 删除资料归档信息
	 *
	 * @param guid 资料归档ID
	 * @return 结果
	 */
	@Override
	public int deleteBmsBusinessDocArchiveByGuid(String guid) {
		return bmsBusinessDocArchiveMapper.deleteBmsBusinessDocArchiveByGuid(guid);
	}

	/**
	 * 根据项目ID查询该项目下资料归档
	 *
	 * @param projectId 项目id
	 * @return 结果
	 */
	@Override
	public List<BmsBusinessDocArchive> selectBmsBusinessDocArchiveListByProjectId(String projectId) {
		return bmsBusinessDocArchiveMapper.selectBmsBusinessDocArchiveListByProjectId(projectId);
	}

	@Override
	public ArchiveStatusVo selectArchiveAllStatus(String businessId) {
		ArchiveStatusVo archiveStatusVo = new ArchiveStatusVo();
		if (businessId != null && !"".equals(businessId)) {
			BmsBusiness bmsBusiness = bmsBusinessMapper.selectBmsBusinessByGuid(businessId);
			archiveStatusVo.setArchiveStatus(bmsBusiness.getArchiveStatus());
			BmsBusinessDocArchive businessDocArchive = new BmsBusinessDocArchive();
			businessDocArchive.setBusinessId(businessId);
			List<BmsBusinessDocArchive> businessDocArchives = bmsBusinessDocArchiveMapper
					.selectBmsBusinessDocArchiveList(businessDocArchive);
			String flag = "1";
			for (BmsBusinessDocArchive item : businessDocArchives) {
				if ("1".equals(item.getMustFlag())) {
					if ((item.getAttachments().size() == 0 || "".equals(item.getAttachments().get(0).getFileId()))
							&& ("".equals(item.getRemark()) || item.getRemark() == null)) {
						flag = "0";
					}
				}
			}

			archiveStatusVo.setFlag(flag);
		}
		// 查询登陆人是否是项目经理或者项目负责人
		String canEdit = bmsBusinessDocArchiveMapper
				.checkUser(tokenService.getLoginUser(ServletUtils.getRequest()).getUser().getUserId(), businessId);
		archiveStatusVo.setCanEdit(canEdit);
		return archiveStatusVo;
	}

	@Override
	public List<DocArchiveVo> selectDocArchiveByBusinessId(String businessId) {

		List<BmsBusinessDocArchive> list = bmsBusinessDocArchiveMapper.selectDocArchiveByBusinessId(businessId);
		List<DocArchiveVo> newList = new ArrayList<DocArchiveVo>();
		if (list != null && list.size() > 0) {
			list.forEach(item -> {
				if (item.getAttachments() != null && item.getAttachments().size() > 1) {
					for (int i = 0; i < item.getAttachments().size(); i++) {
						DocArchiveVo docArchiveVo = new DocArchiveVo();
						docArchiveVo.setFileName(item.getName());
						docArchiveVo.setAttachmentName(item.getAttachments().get(i).getFileName());
						docArchiveVo.setWhetherMust("0".equals(item.getMustFlag()) ? "否" : "是");
						if (item.getAttachments().get(i).getStoragePath() != null
								&& !"".equals(item.getAttachments().get(i).getStoragePath())) {
							docArchiveVo.setLink(http + ip + Constants.RESOURCE_PREFIX
									+ item.getAttachments().get(i).getStoragePath());
						}
						docArchiveVo.setInstructions(item.getRemark());
						newList.add(docArchiveVo);
					}
				} else {
					DocArchiveVo docArchiveVo = new DocArchiveVo();
					docArchiveVo.setFileName(item.getName());
					docArchiveVo.setAttachmentName(item.getFileName());
					docArchiveVo.setWhetherMust("0".equals(item.getMustFlag()) ? "否" : "是");
					if (item.getStoragePath() != null && !"".equals(item.getStoragePath())) {
						docArchiveVo.setLink(http + ip + Constants.RESOURCE_PREFIX + item.getStoragePath());
					}
					docArchiveVo.setInstructions(item.getRemark());
					newList.add(docArchiveVo);
				}

			});
		}

		return newList;
	}

	@Override
	public List<BmsBusinessDocArchive> selectBmsBusinessDocArchiveListInDocQuery(
			BmsBusinessDocArchive bmsBusinessDocArchive) {
		return bmsBusinessDocArchiveMapper.selectBmsBusinessDocArchiveListInDocQuery(bmsBusinessDocArchive);
	}

	@Override
	public List<BmsAttachmentDto> selectAttachments(BmsBusinessDocArchive bmsBusinessDocArchive) {

		List<BmsAttachmentDto> list = bmsBusinessDocArchiveMapper.selectAttachments(bmsBusinessDocArchive);
		if (list != null && list.size() > 0) {
			list.forEach(item -> {
				if (StringUtils.isNotBlank(item.getFileId())) {
					item.setStoragePath(http + ip + Constants.RESOURCE_PREFIX + item.getStoragePath());
				}
			});
		}

		return list;
	}
}
